package com.github.jlmd.animatedcircleloadingview.sample;

import com.github.jlmd.animatedcircleloadingview.AnimatedCircleLoadingView;
import ohos.aafwk.ability.Ability;
import ohos.aafwk.content.Intent;
import ohos.app.dispatcher.TaskDispatcher;
import ohos.app.dispatcher.task.TaskPriority;

import java.util.logging.Level;
import java.util.logging.Logger;

public class MainAbility extends Ability {
    private AnimatedCircleLoadingView animatedCircleLoadingView;
    private TaskDispatcher globalTaskDispatcher = null;
    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        setUIContent(ResourceTable.Layout_ability_main);
        animatedCircleLoadingView = (AnimatedCircleLoadingView) findComponentById(ResourceTable.Id_circle_loading_view);
        globalTaskDispatcher = getGlobalTaskDispatcher(TaskPriority.DEFAULT);
        startLoading();
        startPercentMockThread();

    }

    private void startLoading() {
        animatedCircleLoadingView.startDeterminate();
    }

    private void startPercentMockThread() {
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(1500);
                    for (int i = 0; i <= 100; i++) {
                        Thread.sleep(65);
                        changePercent(i);
                    }
                } catch (InterruptedException e) {
                    Logger.getLogger(MainAbility.class.getName()).log(Level.SEVERE,e.getMessage());
                }
            }
        };
        globalTaskDispatcher.asyncDispatch(runnable);
    }

    private void changePercent(final int percent) {
        getContext().getUITaskDispatcher().asyncDispatch(new Runnable() {
            @Override
            public void run() {
                animatedCircleLoadingView.setPercent(percent);
            }
        });
    }

    public void resetLoading() {
        getContext().getUITaskDispatcher().asyncDispatch(new Runnable() {
            @Override
            public void run() {
                animatedCircleLoadingView.resetLoading();
            }
        });
    }
}
